package com.mk.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mk.seckill.mapper.SeckillOrderMapper;
import com.mk.seckill.pojo.SeckillOrder;
import com.mk.seckill.pojo.User;
import com.mk.seckill.service.ISeckillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
//@Primary
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Long getResult(User user, Long goodsId) {
        /**
         * @Author hhwu
         * @Description //TODO 获取秒杀结果	 orderId:成功，-1：秒杀失败，0：排队中
         * @Date 11:30 2022/6/13
         * @Param [user, goodsId]
         * @return java.lang.Long
         **/

        SeckillOrder seckillOrder = seckillOrderMapper.selectOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
//        // 秒杀成功的订单不仅在数据库中存有，在redis中也存有，就是为了同一个人多次秒杀同一件商品时，快速返回订单结果
//        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);// 从redis中获取（优化）
        if (null != seckillOrder) {// 秒杀成功
            return seckillOrder.getOrderId();
        } else if (redisTemplate.hasKey("isStockEmpty:" + goodsId)) {// redis的库存数量为空时，秒杀失败。注意这里的库存判断是在异步下单的过程中再进行一次，而和下单前判断库存不冲突。
            return -1L;
        } else {// 下单中
            return 0L;
        }

    }
}
